package br.ufrn.cursoResidencia.repositorio;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import br.ufrn.cursoResidencia.dominio.Convenio;

@Repository
public class RepositorioConvenio extends HibernateDaoSupport {
	
	@Autowired
	public RepositorioConvenio(SessionFactory sf) {
		setSessionFactory(sf);
	}
	public boolean convenioJaExiste(Convenio convenio){
		DetachedCriteria criteria=DetachedCriteria.forClass(convenio.getClass());
		criteria.add(Restrictions.eq("id", convenio.getId()));
		return getHibernateTemplate().findByCriteria(criteria).size()>0 ;
		
	}

	public void inserir(Convenio conv) throws Exception{
		if(convenioJaExiste(conv))
			throw new Exception("O Convênio já existe");
		else{
			Session session= getSessionFactory().openSession();
			session.saveOrUpdate(conv);
			session.flush();
		}
	}

}
